package com.ld.shieldsb.verifycode.service.impl;

import java.awt.FontFormatException;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.ld.shieldsb.verifycode.service.VerifyCodeService;
import com.ld.shieldsb.verifycode.util.ConfigExtend;

import lombok.extern.slf4j.Slf4j;

/**
 * 验证码工具
 * 
 * @ClassName VerifyCodeUtil
 * @author <a href="mailto:donggongai@126.com" target="_blank">吕凯</a>
 * @date 2019年6月25日 上午8:37:08
 *
 */
@Slf4j
public class GoogleKaptchaService extends VerifyCodeService {
    public static final DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
    static {
        Properties properties = new Properties();
        ConfigExtend config = new ConfigExtend(properties); // 改为自定义的config，读取配置文件，修改后实时生效
        defaultKaptcha.setConfig((Config) config);
    }

    public boolean out(HttpServletRequest request, HttpServletResponse response, String sessionKeyCode)
            throws IOException, FontFormatException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        // 生成验证码
        String capText = defaultKaptcha.createText();
        String result = null; // 验证码结果
        String capStr = null; // 验证码表达式
        String type = CONFIG.getString("easy.kaptcha.imgtype", "").toLowerCase(); // 判断是算术还是普通验证码
        if (type.contains("arith")) { // 算术
            capStr = capText.substring(0, capText.lastIndexOf("@")); // 截取算术验证码表达式
            result = capText.substring(capText.lastIndexOf("@") + 1); // 截取算术验证码结果
        } else {
            capStr = result = capText;
        }
        saveVerifyCode2Session(request.getSession(), result, sessionKeyCode);
        // 向客户端输出表达式（算术）或者结果（文本）
        BufferedImage bi = defaultKaptcha.createImage(capStr);
        try (ServletOutputStream out = response.getOutputStream()) {
            ImageIO.write(bi, "jpg", out);
            out.flush();
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

}